import { Timeline } from "@mui/lab";
import {
  TimelineConnector,
  TimelineContent,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Paper, Typography } from "@mui/material";
import React from "react";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import PauseCircleFilledIcon from "@mui/icons-material/PauseCircleFilled";
import AccessTimeFilledIcon from "@mui/icons-material/AccessTimeFilled";
import Button from "@mui/material/Button";
import { useContext } from "react";
import { TitleContext } from "../../../router";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";
// import { queryClient } from "../../../query/CustomQueryClient";
// import useExamPlan from "../../../query/useExamPlan";
// import useScore from "../../../query/useScore";
import { useState } from "react";
import Loading from "../../../components/loading";
import { Box } from "@mui/system";
import examBeginUrl from "../../../img/exambegin.gif";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { useMutation } from "@tanstack/react-query";
import examEndUrl from "../../../img/examend.gif";
import { GET_EXAM_URL } from "../../../constants/url";

const formatDate = (date, fmt) => {
  if (typeof date == "string") {
    return date;
  }

  if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";

  if (!date || date == null) return null;
  var o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  }
  return fmt;
};
export default function ExamPlan() {
  const {
    data: exams,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getExam"], mutateQueryFn);

  useEffect(() => {
    getMutate({ url: GET_EXAM_URL, method: "get", useToken: true });
  }, []);

  const [rows, setRows] = useState([]);

  // useEffect(() => {
  //   queryClient.clear();
  // }, []);
  // const [plandata, setPlandata] = useState([]);

  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(6);
  });

  // const { data, isFetching, isError, error, isSuccess } = useExamPlan();
  const data = [
    {
      cid: "001",
      name: "离散数学期末考试",
      date: "2022-11-15",
      betime: "14:00",
      endtime: "16:00",
      area: "学生在线会议室",
    },
    {
      cid: "002",
      name: "概率论与数理统计",
      date: "2022-11-16",
      betime: "14:00",
      endtime: "16:00",
      area: "学生在线会议室",
    },
    {
      cid: "003",
      name: "高等数学",
      date: "2022-12-17",
      betime: "14:00",
      endtime: "22:00",
      area: "学生在线会议室",
    },
    {
      cid: "004",
      name: "计算机组成原理",
      date: "2023-1-06",
      betime: "14:00",
      endtime: "16:00",
      area: "学生在线会议室",
    },
  ];
  const isFetching = false;
  const isSuccess = true;

  const nowDate = formatDate(new Date(), "yyyy-MM-dd");
  const nowTime = formatDate(new Date(), "hh:mm");

  const handleChange = (e) => {
    //
    if (nowDate < e.date) return 3;
    if (nowDate > e.date) return 1;
    if (nowTime > e.endtime) return 1;
    if (nowTime < e.betime) return 3;
    return 2; //2是当天 1是已经结束 3是还未开始；2,3只能查看考试名单；1时可以录入成绩；
  };

  const navigate = useNavigate();
  const handleClick = (e) => {
    navigate("/teacher/homepage/examdetail/", {
      state: { id: e.id, courseId: e.courseId, isEnd: e.isEnd, name: e.name },
    });
  };

  return (
    <div>
      <Paper sx={{ width: "98%", paddingTop: "50px", minHeight: "600px" }}>
        {getLoading && <Loading />}
        {getSuccess && !getLoading && (
          <>
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <img
                alt="BEGIN"
                style={{ width: "65px", marginBottom: "-20px" }}
                src={examBeginUrl}
              ></img>
            </Box>
            <Timeline position="alternate">
              {exams.data.data.map((value) => {
                if (value.status === 1) {
                  return (
                    <TimelineItem>
                      <TimelineOppositeContent
                        sx={{ m: "auto 0" }}
                        align="right"
                        variant="body2"
                        color="text.secondary"
                      >
                        <Typography> {value.date}</Typography>
                        {value.betime + "-" + value.endtime}
                      </TimelineOppositeContent>

                      {/* <TimelineDot color="primary" variant="filled"> */}
                      {handleChange(value) === 1 && (
                        <>
                          <TimelineSeparator>
                            <TimelineConnector
                              sx={{ bgcolor: "secondary.main" }}
                            />
                            <CheckCircleIcon
                              fontSize="large"
                              color="success"
                              variant="filled"
                            />
                            <TimelineConnector
                              sx={{ bgcolor: "secondary.main" }}
                            />
                          </TimelineSeparator>
                          <TimelineContent sx={{ py: "12px", px: 2 }}>
                            <Typography variant="h6" component="span">
                              {value.name}
                            </Typography>
                            <Typography>{"考试地点:" + value.area}</Typography>
                            <Button
                              variant="text"
                              onClick={() =>
                                handleClick({
                                  id: value.id,
                                  courseId: value.courseId,
                                  isEnd: true,
                                  name: value.name,
                                })
                              }
                            >
                              考试已结束 点击录入考试成绩
                            </Button>
                          </TimelineContent>
                        </>
                      )}
                      {handleChange(value) === 2 && (
                        <>
                          <TimelineSeparator>
                            <TimelineConnector
                              sx={{ bgcolor: "secondary.main" }}
                            />
                            <PauseCircleFilledIcon
                              fontSize="large"
                              color="primary"
                              variant="filled"
                            />
                            <TimelineConnector />
                          </TimelineSeparator>
                          <TimelineContent sx={{ py: "12px", px: 2 }}>
                            <Typography variant="h6" component="span">
                              {value.name}
                            </Typography>
                            <Typography>{"考试地点:" + value.area}</Typography>
                            <Button
                              variant="text"
                              onClick={() =>
                                handleClick({
                                  id: value.id,
                                  courseId: value.courseId,
                                  isEnd: false,
                                  name: value.name,
                                })
                              }
                            >
                              考试进行中 点击查看考试名单
                            </Button>
                          </TimelineContent>
                        </>
                      )}
                      {handleChange(value) === 3 && (
                        <>
                          <TimelineSeparator>
                            <TimelineConnector />
                            <AccessTimeFilledIcon
                              fontSize="large"
                              color="warning"
                              variant="filled"
                            />
                            <TimelineConnector />
                          </TimelineSeparator>
                          <TimelineContent sx={{ py: "12px", px: 2 }}>
                            <Typography variant="h6" component="span">
                              {value.name}
                            </Typography>
                            <Typography>{"考试地点:" + value.area}</Typography>
                            <Button
                              variant="text"
                              onClick={() =>
                                handleClick({
                                  id: value.id,
                                  courseId: value.courseId,
                                  isEnd: false,
                                  name: value.name,
                                })
                              }
                            >
                              考试未开始 点击查看考试名单
                            </Button>
                          </TimelineContent>
                        </>
                      )}
                      {/* </TimelineDot> */}
                    </TimelineItem>
                  );
                } else {
                  return undefined;
                }
              })}
            </Timeline>
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <img
                alt="END"
                style={{ width: "65px", marginTop: "-30px" }}
                src={examEndUrl}
              ></img>
            </Box>
          </>
        )}
      </Paper>
    </div>
  );
}
